<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="header">
			<text class="header-title">{{ isEditMode ? '编辑车辆' : '添加车辆' }}</text>
		</view>

		<!-- 表单内容 -->
		<view class="form-container">
			<!-- 车牌号输入 -->
			<view class="form-section">
				<view class="section-title">车牌号码 <text class="required">*</text></view>
				<view class="input-group">
					<textarea class="form-input form-textarea" :class="{ error: plateNumberError }"
						v-model="formData.plate_number" placeholder="请输入车牌号，如：京A12345" maxlength="15"
						:auto-height="false" :show-confirm-bar="false" @input="onPlateNumberInput"
						@blur="validatePlateNumber" />
					<view class="input-error" v-if="plateNumberError">
						<text class="error-text">{{ plateNumberError }}</text>
					</view>
				</view>
			</view>

			<!-- 车辆类型选择 -->
			<view class="form-section">
				<view class="section-title">车辆类型 <text class="required">*</text></view>
				<view class="selector-group">
					<picker :range="vehicleTypeOptions" :range-key="'label'" :value="selectedTypeIndex"
						@change="onVehicleTypeChange">
						<view class="selector-display">
							<text class="selector-text">
								{{ selectedVehicleType ? selectedVehicleType.label : '请选择车辆类型' }}
							</text>
							<text class="selector-arrow">></text>
						</view>
					</picker>
					<view class="input-error" v-if="vehicleTypeError">
						<text class="error-text">{{ vehicleTypeError }}</text>
					</view>
				</view>
			</view>

			<!-- 车辆品牌 -->
			<view class="form-section">
				<view class="section-title">车辆品牌</view>
				<view class="input-group">
					<textarea class="form-input form-textarea" v-model="formData.brand" placeholder="请输入车辆品牌，如：丰田"
						maxlength="50" :auto-height="false" :show-confirm-bar="false" @blur="validateBrand" />
					<view class="input-error" v-if="brandError">
						<text class="error-text">{{ brandError }}</text>
					</view>
				</view>
			</view>

			<!-- 车辆型号 -->
			<view class="form-section">
				<view class="section-title">车辆型号</view>
				<view class="input-group">
					<textarea class="form-input form-textarea" v-model="formData.model" placeholder="请输入车辆型号，如：卡罗拉"
						maxlength="50" :auto-height="false" :show-confirm-bar="false" @blur="validateModel" />
					<view class="input-error" v-if="modelError">
						<text class="error-text">{{ modelError }}</text>
					</view>
				</view>
			</view>

			<!-- 车辆颜色 -->
			<view class="form-section">
				<view class="section-title">车辆颜色</view>
				<view class="selector-group">
					<picker :range="vehicleColorOptions" :value="selectedColorIndex" @change="onVehicleColorChange">
						<view class="selector-display">
							<text class="selector-text">
								{{ formData.color || '请选择车辆颜色' }}
							</text>
							<text class="selector-arrow">></text>
						</view>
					</picker>
					<view class="input-error" v-if="colorError">
						<text class="error-text">{{ colorError }}</text>
					</view>
				</view>
			</view>

			<!-- 数据完整性提示 -->
			<view class="completeness-tip" v-if="completenessInfo.completeness < 100">
				<view class="tip-header">
					<text class="tip-title">信息完整度：{{ completenessInfo.completeness }}%</text>
				</view>
				<text class="tip-content">{{ completenessInfo.suggestions }}</text>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<button class="submit-btn" :class="{ disabled: !canSubmit }" :disabled="!canSubmit || loading"
				@click="submitForm">
				{{ loading ? '保存中...' : (isEditMode ? '保存修改' : '添加车辆') }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import vehicleStorage from '../../utils/vehicleStorage.js'
import vehicleValidator from '../../utils/vehicleValidator.js'

// 响应式数据
const isEditMode = ref(false)
const vehicleId = ref('')
const loading = ref(false)

// 表单数据
const formData = ref({
	plate_number: '',
	vehicle_type: '',
	brand: '',
	model: '',
	color: ''
})

// 错误信息
const plateNumberError = ref('')
const vehicleTypeError = ref('')
const brandError = ref('')
const modelError = ref('')
const colorError = ref('')

// 车辆类型选项
const vehicleTypeOptions = ref([
	{ value: 'small', label: '小型车' },
	{ value: 'medium', label: '中型车' },
	{ value: 'large', label: '大型车' },
	{ value: 'suv', label: 'SUV' },
	{ value: 'truck', label: '货车' }
])

// 车辆颜色选项
const vehicleColorOptions = ref([
	'白色', '黑色', '银色', '灰色', '红色',
	'蓝色', '绿色', '黄色', '棕色', '其他'
])

// 计算属性
const selectedTypeIndex = computed(() => {
	return vehicleTypeOptions.value.findIndex(option => option.value === formData.value.vehicle_type)
})

const selectedVehicleType = computed(() => {
	return vehicleTypeOptions.value.find(option => option.value === formData.value.vehicle_type)
})

const selectedColorIndex = computed(() => {
	return vehicleColorOptions.value.findIndex(color => color === formData.value.color)
})

const canSubmit = computed(() => {
	return formData.value.plate_number.trim() &&
		formData.value.vehicle_type &&
		!plateNumberError.value &&
		!vehicleTypeError.value &&
		!brandError.value &&
		!modelError.value &&
		!colorError.value
})

const completenessInfo = computed(() => {
	return vehicleValidator.checkDataCompleteness(formData.value)
})

// 车牌号输入处理
const onPlateNumberInput = () => {
	// 自动转换为大写
	formData.value.plate_number = formData.value.plate_number.toUpperCase()
	// 清除之前的错误信息
	plateNumberError.value = ''
}

// 车牌号验证
const validatePlateNumber = () => {
	const result = vehicleValidator.validatePlateNumber(formData.value.plate_number)
	if (!result.valid) {
		plateNumberError.value = result.message
		return false
	}

	// 检查车牌号是否重复
	const excludeId = isEditMode.value ? vehicleId.value : null
	if (vehicleStorage.isPlateNumberExists(formData.value.plate_number, excludeId)) {
		plateNumberError.value = '该车牌号已存在'
		return false
	}

	plateNumberError.value = ''
	return true
}

// 车辆类型选择
const onVehicleTypeChange = (e) => {
	const index = e.detail.value
	formData.value.vehicle_type = vehicleTypeOptions.value[index].value
	vehicleTypeError.value = ''
}

// 车辆颜色选择
const onVehicleColorChange = (e) => {
	const index = e.detail.value
	formData.value.color = vehicleColorOptions.value[index]
	colorError.value = ''
}

// 品牌验证
const validateBrand = () => {
	const result = vehicleValidator.validateBrand(formData.value.brand)
	if (!result.valid) {
		brandError.value = result.message
		return false
	}
	brandError.value = ''
	return true
}

// 型号验证
const validateModel = () => {
	const result = vehicleValidator.validateModel(formData.value.model)
	if (!result.valid) {
		modelError.value = result.message
		return false
	}
	modelError.value = ''
	return true
}

// 颜色验证
const validateColor = () => {
	const result = vehicleValidator.validateColor(formData.value.color)
	if (!result.valid) {
		colorError.value = result.message
		return false
	}
	colorError.value = ''
	return true
}

// 表单验证
const validateForm = () => {
	let isValid = true

	if (!validatePlateNumber()) isValid = false
	if (!formData.value.vehicle_type) {
		vehicleTypeError.value = '请选择车辆类型'
		isValid = false
	}
	if (!validateBrand()) isValid = false
	if (!validateModel()) isValid = false
	if (!validateColor()) isValid = false

	return isValid
}

// 提交表单
const submitForm = async () => {
	if (!validateForm()) {
		uni.showToast({
			title: '请检查表单信息',
			icon: 'none'
		})
		return
	}

	loading.value = true

	try {
		let result

		if (isEditMode.value) {
			// 编辑模式
			result = vehicleStorage.updateVehicle(vehicleId.value, formData.value)
		} else {
			// 添加模式
			result = vehicleStorage.addVehicle(formData.value)
		}

		if (result.success) {
			uni.showToast({
				title: result.message,
				icon: 'success'
			})

			// 延迟返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			uni.showToast({
				title: result.message,
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('提交表单失败:', error)
		uni.showToast({
			title: '操作失败，请重试',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 加载车辆信息（编辑模式）
const loadVehicleInfo = (id) => {
	const vehicle = vehicleStorage.getVehicleById(id)
	if (vehicle) {
		formData.value = {
			plate_number: vehicle.plate_number,
			vehicle_type: vehicle.vehicle_type,
			brand: vehicle.brand || '',
			model: vehicle.model || '',
			color: vehicle.color || ''
		}
	} else {
		uni.showToast({
			title: '车辆信息不存在',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
}

// 页面加载时获取参数
onLoad((options) => {
	console.log('车辆表单页面加载，参数:', options)

	if (options.id && options.mode === 'edit') {
		isEditMode.value = true
		vehicleId.value = options.id
		loadVehicleInfo(options.id)
	}
})
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.header {
	background-color: #fff;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #eee;
}

.header-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.form-container {
	padding: 20rpx;
}

.form-section {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.required {
	color: #ff4757;
	margin-left: 4rpx;
}

.input-group {
	position: relative;
}

.form-input {
	width: 100%;
	padding: 24rpx 20rpx;
	border: 2rpx solid #ddd;
	border-radius: 8rpx;
	font-size: 30rpx;
	color: #333;
	background-color: #fff;
	box-sizing: border-box;
}

.form-input:focus {
	border-color: #007aff;
}

.form-input.error {
	border-color: #ff4757;
}

.form-textarea {
	height: 80rpx;
	line-height: 32rpx;
	resize: none;
	overflow: hidden;
	word-wrap: break-word;
	word-break: break-all;
}

.selector-group {
	position: relative;
}

.selector-display {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 20rpx;
	border: 2rpx solid #ddd;
	border-radius: 8rpx;
	background-color: #fff;
}

.selector-text {
	font-size: 30rpx;
	color: #333;
}

.selector-arrow {
	font-size: 24rpx;
	color: #999;
	transform: rotate(90deg);
}

.input-error {
	margin-top: 12rpx;
}

.error-text {
	font-size: 24rpx;
	color: #ff4757;
}

.completeness-tip {
	background-color: #fff3cd;
	border: 1rpx solid #ffeaa7;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.tip-header {
	margin-bottom: 8rpx;
}

.tip-title {
	font-size: 26rpx;
	font-weight: bold;
	color: #856404;
}

.tip-content {
	font-size: 24rpx;
	color: #856404;
	line-height: 1.4;
}

.submit-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 30rpx 40rpx;
	border-top: 1rpx solid #eee;
}

.submit-btn {
	width: 100%;
	padding: 30rpx;
	background-color: #007aff;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.submit-btn.disabled {
	background-color: #ccc;
	color: #999;
}
</style>